<?php 

// TODO: make cross-references to different sections	 do this via JS without a reload


session_start();
header("Cache-control: private");



// admin link used; set session & redirect
if ($_GET['key'] == "WN5wKu0nBaZnKZ5Ns1gSiae8VVSf7YuCdLpsC00m") {
	$_SESSION['docid'] = "1";
	header('location:index.php');
}

// agent link used; set session & redirect
if ($_GET['key'] == "chab6o7queug7hu8wiag2ja2hu7wof4bi") {
	$_SESSION['docid'] = "2";
	header('location:index.php');
}

// after page reloads without key in URL:
if ($_SESSION['docid'] == "1") {$admin=1;}
if ($_SESSION['docid'] == "2") {$agent=1;}

include 'includes/functions.php';
echo db_connect();


// SET IT TO DISPLAY CORRECT SECTION, MENU CHAPTER AND HIGHLIGHT SECTION
$section_get = $_GET['s'];

if ($_GET['f']) {
	#DIE (print_r($_GET));
	setcookie("filter", $_GET['f']);
	if ($section_get) $sget = "?s=$section_get";
	header("location:index.php$sget");
}

if ($_COOKIE['filter'] && $_COOKIE['filter'] != 'x') {
	if ($_COOKIE['filter'] == "kf-1") { // filter by known issues
	  $filter_clause = " AND known_issues != ''";   
	}else{ // filter by one of the statuses
	  $filter_clause = " AND status = '".$_COOKIE['filter']."'";    
	}
	
}   

if ($section_get){
	$chapter_lk_sql = "select documentation_chapter_id,section_num from documentation_sections where section_id = '$section_get'";
   $chapter_lk_result = mysql_query($chapter_lk_sql);
	$chapter_lk_row = mysql_fetch_array($chapter_lk_result);
	$chapter_lk = $chapter_lk_row[0];
	$section_lk = $chapter_lk_row[1];
}

if ($admin || $agent) {

	$filterDD = "<select name = 'status_filter' id='status_filter'>\n<option id='sf-x' value='x'>Show All</option>";
	if ($admin) { // don't show statuses to agents, just show all and known issues
		foreach($statuses as $key => $val) {
	 		if ($_COOKIE['filter'] == $key) { $ddx = " selected='selected'"; } else { $ddx = ""; }
	 		$filterDD .= "<option id='sf-$key' value='$key'$ddx>$val</option>\n";
		}
	}
	if ($_COOKIE['filter'] == "kf-1") { $ddy = " selected='selected'"; } else { $ddy = ""; } 
	$filterDD .= "<option id='' value=''>---------------</option>\n<option id='kf-1' value='kf-1'$ddy>Known Issues</option>\n";
	$filterDD .= "</select>\n";
	$chapter_filter = "";  
	
} else {
    $chapter_filter = "WHERE documentation_chapter_id != '34'"; // dev chapter
}

//echo "chapter_lk $chapter_lk        section_lk $section_lk        $chapter_lk_sql";

$content = "<div id='c-0' class='cont_item' style='height:600px; font-size:14px;'><br><br><span id='header' >Welcome to the ClientTracker Online Manual</span><br><br>
<ul>
<li> Expand the Directory at left by clicking on a Chapter. Then click a section to get started.<br></li>
<li> Use the Search field at the top to quickly find a subject.<br></li>
<li> If you are upgrading to v4.0, see Chapters 14 & 15 first.<br></li>
</ul>
<br><br></div>"; 

$sql1 = "SELECT * FROM documentation_chapters $chapter_filter ORDER BY `order`"; //echo $sql1;
$result1 = mysql_query($sql1);

$structure_arr=array();
 
if ($admin) {
	$menu .= "   <li><span class='new_button' id = 'new_section' onClick=\"setFormNew('chapter','new','','')\"> + NEW CHAPTER</span></li>\n";
	} else {
		$back_to_top = "<div class='back_to_top'> <a style='cursor:pointer;color:blue;' onClick='scrollGo(0);'>Back to top</a></div>";
	}

while ($row1 = mysql_fetch_array($result1) )  {
  $chapter_id = $row1[0];
  $chapter_title = $row1[1];
  $chapter_number = $row1[2];
  
  
 
	if ($chapter_lk == $chapter_id) {$chapter_state = "";}else{$chapter_state = "closed";}
   if ($admin == 1) {$chapter_edit_html = "<br><div id='edit_toolbar'><a href='#' onClick=\"setForm('chapter','$chapter_id','$chapter_title','$chapter_number')\">Rename</a> :: Move <a href='edit.php?reorder=1&type=chapter&cid=$chapter_id&direction=up'>up</a>|<a href='edit.php?reorder=1&type=chapter&cid=$chapter_id&direction=down'>down</a></div>";
}else {$chapter_edit_html = "";}    

  $menu .= "<li class='$chapter_state'><span class='folder' style='font-weight:bold;' id ='ch-$chapter_id'>$chapter_number. $chapter_title 
<div>
$chapter_edit_html
</div>
</span>\n  <ul>\n";
  $sql2 = "SELECT DISTINCT(section_num) FROM documentation_sections WHERE documentation_chapter_id = '$chapter_id'$filter_clause ORDER BY section_num";
  $result2 = mysql_query($sql2); if(!$result2) DIE(mysql_error().$sql2);
  while ($row2 = mysql_fetch_array($result2) )  {
	$section_number = $row2[0];
	    $sql3 = "SELECT * FROM documentation_sections WHERE documentation_chapter_id = '$chapter_id' AND section_num = '$section_number'$filter_clause ORDER BY section_num, `order`";  //echo $sql3;
	    $result3 = mysql_query($sql3); if(!$result3) DIE(mysql_error().$sql3);
	    while ($row3 = mysql_fetch_array($result3) )  {
		$section_id_gran = $row3[0]; 
		$section_title = $row3[2];
		$section_text_bit = stripslashes ($row3[3]); $section_text_bit = parse_crossReference($section_text_bit,$section_number,$chapter_id);
		 $section_bit_num = $row3[4];
		$detail_title = $row3[6];
		$status = $statuses [$row3[8]];
		$last_editor = $row3[9];
		$known_issues = $row3['known_issues']; 
		
		#if ($known_issues) {$knownn="&nbsp;<a title='This item has known issues'><span class='known_issues' style='padding:2px'>IS</span></a>";}else{$knownn="";}
	    if ($known_issues) {$knownn="<br><div class='known_issues'><strong>KNOWN ISSUES:</strong><br>$known_issues</div>";}else{$knownn="";}
		$notes = $row3['notes']; 
		
		if ($notes) {$notess="&nbsp;<a title='This item has notes'><span class='notes_note'>NO</span></a>";}else{$notess="";} 
		
		 //$section_text .=  "<div class='bit_head'>".$section_bit_num."</div>".$row3[3];
	    if ($admin == 1) { 
		$editLink = "<br><div id='edit_toolbar' style='margin-top:10px; font-size:11px;'><a href='edit.php?sid=$section_id_gran' >Edit</a> :: Move <a href='edit.php?reorder=1&type=detail&sid=$section_id_gran&direction=up'>up</a>|<a href='edit.php?reorder=1&type=detail&sid=$section_id_gran&direction=down'>down</a>  :: status:<strong>$status</strong>  :: Last edited by:<strong>$last_editor </strong> ::  cross-reference:<span style='color:red; font-weight:bold;'><<$section_id_gran>></span> $notess $knownn</div>";
		$addLink = "<div id='edit_toolbar' style='margin-top:15px; font-size:12px'><a href='edit.php?sid=$section_id_gran&action=new'>+ Add New Section Detail</a></div>";
		}elseif($agent){
		  if ($known_issues) {$editLink="<br><div class='known_issues'><strong>KNOWN ISSUES:</strong><br>$known_issues</div>";} else {$editLink="";}  
		  $addLink="";
		}else{ $editLink=""; $addLink=""; }
		if ($detail_title) { $detail_title_text = "<div class='detail_title'>".$detail_title."</div>";}else{$detail_title_text="";}
	$section_text .=  "<a name='$section_id_gran' id='$section_id_gran'></a>".$detail_title_text.$section_text_bit."$editLink $back_to_top <div class='bit_head'><hr class='hrr'></div>";
	    }


	//$structure_arr[$chapter_number] .= array('section_id' => $row2[0], 'section_num' => $row2[5], 'order' => $row2[4]); 
  
	$content .= "<div id='c-$chapter_id-$section_number' class='cont_item'>\n<div id='chapter_header'>$chapter_number. <strong>$chapter_title</strong> :<span style='color:black;font-size:14px;'>  $section_title</span> </div>\n<br>$section_text $addLink</div>\n";
	if ($admin) { $section_toolbar = "<div id='edit_toolbar' style='margin-top:0px;'> :: <a href='#' onClick=\"setForm('section','$section_id_gran','$section_title','$section_number')\">Rename</a> :: Move <a href='edit.php?reorder=1&type=section&sid=$section_id_gran&direction=up'>up</a>|<a href='edit.php?reorder=1&type=section&sid=$section_id_gran&direction=down'>down</a></div>"; }else{ $section_toolbar=""; }
	$menu .= "   <li><span class='file' id = 'f-$chapter_id-$section_number' onClick=\"showHide('$section_id_gran','$chapter_id-$section_number');\">$section_number. $section_title</span>$section_toolbar</li>\n"; 
   $section_text = "";
	}
if ($admin) $menu .= "   <li><span class='new_button' id = 'new_section' onClick=\"setFormNew('section','$chapter_id','new');\"> + NEW SECTION</span></li>\n";    
$menu .= "  </ul>\n";
}
if ($admin) $menu .= "   <li><span class='new_button' id = 'new_section' onClick=\"setFormNew('chapter','new','')\"> + NEW CHAPTER</span></li>\n";  
$menu .= "</li>\n"; 

if ($section_get) {
  $initial_content = "$('#c-$section_get').fadeIn('fast');scrollGo('$section_get');\n";
 }else{
  $initial_content = "$('#c-0').fadeIn('fast');\n";
}

if ($_GET['msg'] == 'd') $msg="<div class='msg'>Record was successfully deleted.</div>"; 

?>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<link rel="stylesheet" href="css/screen.css" type="text/css" />
<link rel="stylesheet" href="css/app_styles.css" type="text/css" />
<link rel="stylesheet" href="css/styles.css" type="text/css" />   
<link rel="stylesheet" href="css/jquery.treeview.css" type="text/css" />
<script type="text/javascript" src="includes/jquery.treeview.js"></script>
<script type="text/javascript" src="includes/index.js"></script>  
<script type="text/javascript" charset="utf-8">
	$(document).ready(function(){
	   
		$("#menu").treeview();
		 $("#search").focus();
		 $("#status_filter").change(function(){
			var ptone = window.location.href.split('#')[0];
			
			if (window.location.href.split('?')[1]) { var pttwo = "&f="; }else{ var pttwo = "?f="; }
			self.location = ptone+pttwo+$(this).val();
		});
		
		setTimeout ($(".msg").fadeOut('slow'), 30000); 
		
	<?php if ($section_get) { echo "$('#f-$chapter_lk-$section_lk').css('background-color', '#eee');$('#c-$chapter_lk-$section_lk').show();"; } ?>   
		 $("[class=folder]").click(function() {
			
				var currentId = $(this).attr('id');
				var openOne = $("#selected").val();
				if (openOne != "") {
					//$('#selected').val('');
					//$("#"+openOne).click(); // close open one 
					//setTimeout ("$('#selected').val(currentId);",1000); // save current one as open. timeout to stop recursion  	
					
				}
				
				 
				 
			   
		 });
		
		 
		
		
		$(function() {
			/**
			 * The "historyadd" event is triggered whenever navigation occurs.
			 * In this demonstration, this is the result of the onclick function above.
			 * You may attach this event to as many elements as you wish.
			 */
			$('#status').historyadd(function(e, currentHash, previousHash) {
				$(this).html('Navigation added: ' + currentHash);
			});

			/**
			 * The "history" event is triggered whenever the user presses the back button 
			 * or jumps backwards or forwards in their browser's history list.
			 * You may attach this event to as many elements as you wish
			 */
			$('#status').history(function(e, currentHash, previousHash) {
				if(currentHash == '') {
					currentHash = 'Default Page';
				}
				$(this).html('User navigated to: ' + currentHash);
			});

			/**
			 * The 'history' and 'historyadd' events can be attached to window to allow for global events
			 */
			$(window).history(function(e, hash) {
				if(hash == '') {
					hash = 'Default Page';
				}
				//alert('User navigated to: ' + hash || 'Default Page');
				
				// close all folders
				for (x=0;x<=50;x=x+1) {
				  $('li.collapsable span:first').click();
				}
				// open current folder
				var myarray = hash.split("-");
				$('span[id=ch-'+myarray[0]+']').click()
				
				$("*[id^=c-]").hide(); 
				$('#c-'+hash).fadeIn('fast');

				// highlight menu item
				$("*[id^=f-]").css('background-color', 'white'); 
				$('#f-'+hash).css('background-color', '#eee');
				
				
			});

			/**
			 * Use getCurrent() function to get the hash for the initial load or if the user refreshes the page
			 */
			var initialHash = $.history.getCurrent();
			if(initialHash == '') {
				initialHash = 'Default Page';
			}
			$('#status').html('The initial load is: ' + initialHash);
		});
		
	  
		
		$("#save").click(function() { 
			var formData = $("#ajaxForm").serialize();
			//alert (formData);
			$.post("_save.php", formData, function(data){
			  if (data != 'error') {
				 showHidePopup('hide', "");
				 if (($('#section_id').val() != 'new') && ($('#chapter_id').val() != 'new')) {
					target_id = $('#section_id').val(); // we're renaming, so get existing id 
					//alert(target_id);
				} else { 
					target_id = data; // get inserted id 
					} 
				window.location='index.php?s='+target_id;
			  }else {
				alert('error');
			}
			});
			
			 
		});
		
		
		
		 <?=$initial_content?>
	  });
	
function showHide(section_id,chapt_section_num) {
	// close all folders
	for (x=0;x<=50;x=x+1) {
	  $('li.collapsable span:first').click();
	}
	// open current folder
	var myarray = chapt_section_num.split("-");
	$('span[id=ch-'+myarray[0]+']').click()
	
	// hide all content divs, show current one
	$("*[id^=c-]").hide(); 
	$('#c-'+chapt_section_num).fadeIn('fast');
	
	// highlight menu item
	$("*[id^=f-]").css('background-color', 'white'); 
	$('#f-'+chapt_section_num).css('background-color', '#eee');
	
	// save history
	$.history.add(chapt_section_num); 
	
	// scroll to top
	window.scroll(0,0); 
} 

function setForm(type,id,title,number) {
   showHidePopup('show', 'Rename '+type+' '+number)
	$("#"+type+"_id").val(id);
	$("#section_num").val(number);
	$("#form_title").val(title);
}

function setFormNew(type,chapter_id,section_id) {
   showHidePopup('show', '<strong>New '+type+':</strong> What will it be called?')
	$("#chapter_id").val(chapter_id);
	$("#section_id").val(section_id);
}

function showHidePopup(which, what) {
	if (which == 'show') {
	  	$('#text_window_container').html(what);
		$('#text_window').fadeIn('fast');
		$('#bg_blanker').fadeIn('fast'); 
	} 
	
	if (which == 'hide') {
	  $('#text_window').fadeOut('fast');
	  $('#bg_blanker').fadeOut('fast');
	} 
} 

function scrollGo(id) {
	if (id == 0) {
		$('html,body').animate({scrollTop: 0}, 1000);
	} else {
		var x = $('#'+id).offset().top - 100; // 100 provides buffer in viewport
	   $('html,body').animate({scrollTop: x}, 1000);
	}
}

function clearField()
{
var fldVal = $('#search').val();
if (fldVal == "Search") { $('#search').val(''); }
}

function fillField()
{
var fldVal = $('#search').val(); 
if (fldVal == "") { $('#search').val('Search'); }
}


</script>
<title>ClientTracker Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css" media="screen">
  
	
</style>
</head>

<body>
<div id="text_window">
 <div id="text_window_X" onClick="showHidePopup('hide','');">X</div>
 <div id="text_window_container" class="body"></div>
	<form id='ajaxForm' name='ajaxForm' autocomplete='off'>
  		<input type="hidden" name="chapter_id" value="" id="chapter_id">
		<input type="hidden" name="section_id" value="" id="section_id">
		<input type="hidden" name="section_num" value="" id="section_num">
  		<input type="text" size="45" name="form_title" value="" id="form_title">
  		<input type="button" name="save" value="Save Change" id="save">
  </form>
</div>
<div id="bg_blanker"></div>


<div class="header">ClientTracker Manual <span class='version'>Version 4.0</span>
	 
<?php 
  if ($admin) echo "Admin Mode : $filterDD  <span id='edit_toolbar'><a href='admin/login.php'>Log out</a></span> ";
  if ($agent) echo "Agent Mode : $filterDD  <span id='edit_toolbar'><a href='admin/login.php'>Log out</a></span> ";
?>
	
<?=$msg?>
</div>
<div class="left_tree">
<ul id="menu" class="filetree">
	  <?=$menu?>
 </ul>
 <div class='copyright'>&copy; Entire contents 2011 Ginkgo Software.<br>All Rights Reserved.</div>
</div>
<div class="main" id = "content"><?=$content?></div>
<form action="index_submit" method="get" accept-charset="utf-8">
<input type="hidden" name="selected" value="" id="selected">
</form>
<div id='searchdiv'>
  <form action="search.php" method="get" accept-charset="utf-8">
	<input type="text" name="search" class="input_search" id="search" onFocus="clearField();" onBlur="fillField();">
	<input type="submit" name="some_name" value="Go" id="search" >
  </form>
  <div class='searchbox_note' style=''>Enter single keywords for best results</div>
</div>

</body>
</html>